﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Agro.Models;
using SN.Data;
using System.Data;
namespace Agro.Services {
    public class OrganizationService : BaseService, IOrganizationService {
        const string OrganizeCacheKey = "_Organize_";

        public bool SaveOrganization(Models.T_Organization model, out string msg) {
            msg = string.Empty;
            using (DbTrans trans = DB.BeginTrans()) {
                try {
                    if (model.Organization_ID > 0) {
                        //判断单位编号是否重复,注释掉的原因，因从原系统导入的数据中，存在Organization_Code相同，但Organization_id不同，所以不再判断。
                        //if (DB.Exists<T_Organization>(T_Organization._.Organization_Code == model.Organization_Code && T_Organization._.Organization_ID != model.Organization_ID)) {
                        //    throw new Exception("单位编号已经存在!");
                        //}
                        model.Attach();
                    }
                    else {
                        //新增
                        if (DB.Exists<T_Organization>(T_Organization._.Organization_Code == model.Organization_Code)) {
                            throw new Exception("单位编号已经存在!");
                        }
                        model.Organization_IsDetail = "0"; //是明细
                        //更新父亲结点
                        trans.Update<T_Organization>(T_Organization._.Organization_IsDetail, "1", T_Organization._.Organization_ID == model.Organization_ParentID);
                        model.Detach();
                    }
                    trans.Save(model);
                    //提交事务
                    trans.Commit();
                    RemoveOrganizeCache();
                }
                catch (Exception ex) {
                    msg = ex.Message;
                    trans.Rollback();
                    return false;
                }
            }
            return true;
        }

        public int DeleteOrganization(string id, string pid, int childNum) {
            int returnValue = 0;
            int iCount = 0;
            using (DbTrans trans = BaseService.DB.BeginTrans()) {
                try {
                    //判断是否允许删除 
                    //后台验证是否有下级节点
                    iCount = trans.Count<T_Organization>(T_Organization._.Organization_ParentID == id);
                    if (iCount > 0) {
                        throw new Exception("不是末级单位，不允许删除!");
                    }
                    //判断该单位是否有数据
                    iCount = trans.Count<T_SubmitInfo>(T_SubmitInfo._.SubmitInfo_OrganizationID == id);
                    if (iCount > 0) {
                        throw new Exception("该单位存在报表数据，不允许删除!");
                    }

                    returnValue = trans.Delete<T_Organization>(T_Organization._.Organization_ID == id);

                    if (returnValue == 1 && childNum == 1) {
                        trans.Update<T_Organization>(T_Organization._.Organization_IsDetail, "0", T_Organization._.Organization_ID == pid);
                    }
                    //提交数据
                    trans.Commit();
                    RemoveOrganizeCache();
                }
                catch (Exception ex) {
                    trans.Rollback();
                    returnValue = -1;
                    throw;
                }
            }
            return returnValue;
        }

        private static void RemoveOrganizeCache() {
            Agro.Library.MemoryCacheManager manager = new Library.MemoryCacheManager();
            manager.Remove(OrganizeCacheKey);
        }

        public System.Data.DataTable GetOrganizationList(SN.Core.QueryBase query, WhereClip wclip) {
            Field[] fields = { T_Organization._.All };
            var section = DB.From<T_Organization>()
                .Where(wclip);
            var dt = section.ToTablePage(query, fields);
            return dt;
        }
        public int GetCountOrgByType(int orgid, string type) {
            return DB.Count<T_Organization>(T_Organization._.Organization_ParentID == orgid && T_Organization._.Organization_Type == type);
        }

        public DataTable GetCXJG(int orgid)
        {
            return DB.FromProc("cxjg",new SQLParameter("@bmbh",orgid)).ToDataTable();
        }
        public DataTable GetQYCXJG(int orgid)
        {
            return DB.FromProc("qycxjg", new SQLParameter("@bmbh", orgid)).ToDataTable();
        }
        public IList<T_Organization> GetCacheOrganizeList() {
            Agro.Library.MemoryCacheManager manager = new Library.MemoryCacheManager();
            IList<T_Organization> organizeList = manager.Get<IList<T_Organization>>(OrganizeCacheKey);
            if (organizeList == null) {
                organizeList = DB.From<T_Organization>().ToList();
                manager.Set(OrganizeCacheKey, organizeList, 5);
            }
            return organizeList;
        }
    }
}
